/*
 *
 * @ProjectName:    my_umi_app
 * @Package:
 * @ClassName:      show_article
 * @Description:    预览文章
 * @Author:         SuPeiSen
 * @CreateDate:     2021/3/8 5:59 下午
 * @UpdateDate:     2021/3/8 5:59 下午
 * @UpdateRemark:   更新说明：
 * @Version:        1.0
 */

import { IRouteComponentProps } from 'umi';
import React, { useEffect, useState } from 'react';
import { HttpStatus } from '@/utils/requests';
import { articleContentImage } from '@/utils/app_fun';
import './style/preview_article.less';
import { LoadingWidget } from '@/widget/loading_wdiget/loading_widget';
import { Button } from 'antd';
import { GetArticleDetailsByAdminApi } from '@/service/article_api';
import { ArticleListItemType } from '@/type/article_type';

export default (props: IRouteComponentProps<{}, { id: string }>) => {
  // 请求状态
  const [status, setStatus] = useState<HttpStatus>(HttpStatus.loading);

  // 刷新
  const [refresh, serRefresh] = useState<number>(0);

  // 保存文章详情
  const [articleContent, setArticleContent] = useState<ArticleListItemType>();

  // 获取文章
  useEffect(() => {
    GetArticleDetailsByAdminApi(Number(props.location.query.id)).then(
      (model) => {
        if (model.success) {
          document.title = model!.data?.data?.article_title ?? '';
          setArticleContent(model.data!.data);
          setStatus(HttpStatus.success);
        } else {
          setStatus(HttpStatus.error);
        }
      },
    );
  }, [props.location.query.id, refresh]);

  useEffect(() => {
    require('@/static/src/prism/prism');
    require('@/static/src/prism/prism.css');
    // @ts-ignore
    Prism.highlightAll();
  });

  // loading
  if (status === HttpStatus.loading) {
    return <LoadingWidget />;
  }

  // 请求失败
  if (status === HttpStatus.error) {
    return <div>error....</div>;
  }

  return (
    <div>
      <Button
        onClick={() => {
          setStatus(HttpStatus.loading);
          const newData = refresh + 1;
          serRefresh(newData);
        }}
      >
        刷新
      </Button>
      <div
        style={{ width: '90%' }}
        className={'article_content_html'}
        dangerouslySetInnerHTML={{
          __html: articleContentImage(articleContent!.article_content),
        }}
      />
    </div>
  );
};
